package start.demo01.fileIO;

import org.junit.Test;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class NIOTest {

    @Test public void main() throws IOException {
        String path="../test.txt";//默认的根是当前模块根
        String name="../scores.txt";
        File f=new File(name);
        System.out.println(f.getAbsolutePath()+f.exists());
        fileCopyNIO(name,path);
    }
    public static void fileCopyNIO(String source, String target){//使用NIO实现文件转移
        try (FileInputStream in = new FileInputStream(source)) {
            try (FileOutputStream out = new FileOutputStream(target)) {
                FileChannel inChannel = in.getChannel();
                FileChannel outChannel = out.getChannel();
                ByteBuffer buffer = ByteBuffer.allocate(4096);//分配4096個字節緩存空間
                while (inChannel.read(buffer) != -1) {
                    //当我们需要读取我们刚才写入缓冲区的数据时，首先需要做的是调用缓冲区的flip() 方法，将缓冲区切换到读模式
                    buffer.flip();
                    outChannel.write(buffer);
                    buffer.clear();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void NIO(String source, String target) throws IOException {
        long start = System.currentTimeMillis();
        try (FileChannel inChannel = FileChannel.open(Paths.get(source), StandardOpenOption.READ);
             FileChannel outChannel = FileChannel.open(Paths.get(target), StandardOpenOption.WRITE,
                     StandardOpenOption.READ, StandardOpenOption.CREATE)
        ) {
            long size = inChannel.size();
            for (long left = size; left > 0; ) {
                left -= inChannel.transferTo((size - left), left, outChannel);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
//        LOGGER.info("零拷贝转移耗时:{}s", (System.currentTimeMillis() - start) / 1000.0);
    }
}
